//
//  HomeViewController.m
//  PropertyMananger
//
//  Created by bh on 16/12/21.
//  Copyright © 2016年 BH. All rights reserved.
//

#import "HomeViewController.h"
#import "NotifyView.h"
#import "RepairCell.h"
#import "ToolsMenuCell.h"
#import "NoticeCell.h"

#import "SYNavigationDropdownMenu.h"

#import "AdvertiseController.h"
#import "AttentionController.h"
#import "HouseInfoQueryController.h"
#import "ParkingController.h"
#import "OwnweController.h"
#import "DailyInspectionController.h"
#import "EquipmentManagerController.h"
#import "CheckFormController.h"
#import "FormQueryController.h"
#import "ProprertyPayController.h"
#import "RepairController.h"

#import "MyPublicController.h"
#import "MyComplainController.h"
#import "MyEletricsController.h"
#import "MyWorkController.h"
#import "MessageController.h"
#import "LeaderController.h"
#import "HouseQueryModel.h"
#import "ShakeOpenController.h"
#import "HomeRepairController.h"
#import "HomeComplainController.h"
#import "TitleScrollView.h"

#import "MessageModel.h"
#import "MessageDetController.h"

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,CarouselDataSource,CarouselDelegate,SYNavigationDropdownMenuDataSource, SYNavigationDropdownMenuDelegate>
{
    /**轮播图**/
    CarouselControl * carouselView;
}
/** tableView **/
@property (nonatomic,strong) UITableView * mTableView;
/** 消息通知view **/
@property (nonatomic,strong) NotifyView * notifyView;
@property (nonatomic,strong) NoticeCell * noticeCell;

/**工具菜单数据源**/
@property (nonatomic, strong) NSMutableArray * menuArray;
@property (nonatomic,strong)  NSArray *imagesURL;

@property (nonatomic,strong) NSMutableArray * messageArray;
//输入的搜索关键字
@property (nonatomic,copy) NSString * searchStr;

//楼栋数据源
@property (nonatomic,strong) NSMutableArray * floorArray;
@property (nonatomic,strong) NSString * buiddingID;

@property (nonatomic,strong) NSMutableArray * noticeTitleArr;//消息通知的数据源

//选择小区数据源
@property (nonatomic,strong) NSMutableArray * selectedCommunityNameArr;

@property (nonatomic,copy) NSString * complainttotalCount;//投诉单数量
@property (nonatomic,copy) NSString * repairtotalCount;//报修单单数量
@property (nonatomic,copy) NSString * notReadNoticecount;//未读消息

@property (nonatomic,copy) NSString * myComplaintcount;//我的投诉单数量
@property (nonatomic,copy) NSString * myRepaircount;//我的报修单单数量

@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
    //统计个数
    [self postWorkNumData];
    
    //滚动消息的
    [self postMessageData];
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
   
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = NO;
    //轮播图
    [self createInfiniteScrollView];
    
    [self initData];
    
    //初始化tableview
    [self createTableViewUI];
    
    //获取楼栋数据
   [self postFloorQueryData];
    
    //获取未处理订单数据
    [self postWorkNumData];
    
    [self setupNavigationUI];
    
    //滚动消息的
    [self postMessageData];
    
}
#pragma mark - 初始化数据源
- (void)initData
{
    NSString *plistPath = [[NSBundle mainBundle]pathForResource:@"menuData" ofType:@"plist"];
    self.menuArray = [[NSMutableArray alloc]initWithContentsOfFile:plistPath];
    
    
    self.selectedCommunityNameArr = [[NSMutableArray alloc]init];
    
    NSArray * array = userModel.listArr;
    DLog(@"小区的数组 == %@",array);
    for (CommunitylistModel * model in array) {
              
    [self.selectedCommunityNameArr addObject:model.CommunityName];
        DLog(@"== %@",model.CommunityName);
        
    }
    
    
    self.messageArray = [[NSMutableArray alloc]init];
    self.searchStr = @"";
    
    self.noticeTitleArr = [[NSMutableArray alloc]init];

}
#pragma mark - 初始化tableview
- (void)createTableViewUI
{
    
    self.mTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, BHscreenW, BHscreenH -64-49) style:UITableViewStylePlain];
    self.mTableView.delegate = self;
    self.mTableView.dataSource = self;
    [self.view addSubview:self.mTableView];
    self.mTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.mTableView.showsVerticalScrollIndicator = NO;
    self.mTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.mTableView.tableHeaderView = carouselView;
    //注册

}
#pragma mark - 创建顶部的轮播图
- (void)createInfiniteScrollView {
    
//   _imagesURL = @[         @"http://113.16.167.154:805/Upload/banner/banner01.png",
//                           @"http://113.16.167.154:805/Upload/banner/banner02.png",
//                           @"http://113.16.167.154:805/Upload/banner/banner03.png"
//                           ];
 //   _imagesURL = @[@"banner01",@"banner02",@"banner03"];
  _imagesURL =  @[@{@"image":[UIImage imageNamed:@"banner01"]},
      @{@"image":[UIImage imageNamed:@"banner02"]},
      @{@"image":[UIImage imageNamed:@"banner03"]},
      ];

    carouselView = [[CarouselControl alloc]initWithFrame:CGRectMake(0, 0, BHscreenW, 165)];
    carouselView.carouseScrollTimeInterval = 2.0f;
    carouselView.dataSource = self;
    carouselView.delegate = self;
    [self.view addSubview:carouselView];
    
    /*
     *   必须实现下面重载数据方法
     */
    
    [carouselView reloadData];
    
    
}
#pragma mark --- dataSource
-(NSArray *) zzcarousel:(CarouselControl *)carouselView
{
    return _imagesURL;
}

-(UIView *) zzcarousel:(CarouselControl *)carouselView carouselFrame:(CGRect)frame data:(NSArray *)data viewForItemAtIndex:(NSInteger)index
{
    /*
     *   此方法中必须返回UIView
     *   注意在此方法中创建 UI 控件时，必须使用此方法冲的frame参数来设定位置。
     *   注意在此方法中的数据源必须从data参数中获取。
     */
//    UIView *view = [[UIView alloc]initWithFrame:frame];
//    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
//    [imageView sd_setImageWithURL:[NSURL URLWithString:[data objectAtIndex:index]]];
//    [view addSubview:imageView];
    
    //本地图片
    UIView *view = [[UIView alloc]initWithFrame:frame];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    imageView.image = [[data objectAtIndex:index] objectForKey:@"image"];
    [view addSubview:imageView];
    
    return view;
}
#pragma mark --- delegate跳转广告轮播详情
-(void)zzcarouselView:(CarouselControl *)zzcarouselView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"点击了 %lu",index);
//    AdvertiseController * adverVC = [[AdvertiseController alloc]init];
//    [self.navigationController pushViewController:adverVC animated:YES];
}

#pragma mark - tableview代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 1;
        
    }else if (section == 1)
    {
        return 1;
    }
    else
    {
        return 1;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        
        NoticeCell * cell = [NoticeCell cellWithTableView:tableView];
        
        cell.titleArray = self.messageArray;
        cell.block = ^(NSInteger index){
        
            DLog(@"传过来的index === %ld",index);
            MessageModel * model = self.messageArray[index];
            MessageDetController * messageVC = [[MessageDetController alloc]init];
            messageVC.model  = model;
            [self.navigationController pushViewController:messageVC animated:YES];
        };
        
         return cell;
        
    }else if (indexPath.section == 1)
    {
        RepairCell * repairCell = [RepairCell cellWithTableView:tableView];
        
        repairCell.repairCountLab.text = [NSString stringWithFormat:@"%@",self.myRepaircount];
        repairCell.complainCountLab.text = [NSString stringWithFormat:@"%@",self.myComplaintcount];
        repairCell.messageCountLab.text = [NSString stringWithFormat:@"%@",self.notReadNoticecount];
        
        UITapGestureRecognizer * shakeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shakeAction:)];
        [repairCell.shakeBgView addGestureRecognizer:shakeTap];
        
        UITapGestureRecognizer * repairTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(repairAction:)];
        [repairCell.repairBgView addGestureRecognizer:repairTap];
        
        UITapGestureRecognizer * complaintTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(complaintAction:)];
        [repairCell.complainBgView addGestureRecognizer:complaintTap];
        
        UITapGestureRecognizer * messageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(messageAction:)];
        [repairCell.messageBgView addGestureRecognizer:messageTap];
        
        
        return repairCell;
       
    }else if (indexPath.section == 2)
    {
        ToolsMenuCell * menuCell = [ToolsMenuCell cellWithTableView:tableView menuArray:self.menuArray];
         WEAKSELF_MACRO
        menuCell.block = ^(NSInteger index){
        
            DLog(@"工具菜单栏tag == %ld",index);
            if (index == Attention)
            {//通讯录
                
                AttentionController * attentionVC = [[AttentionController alloc]init];
                attentionVC.title = @"通讯录";
                attentionVC.tag = 300;
                [weakSelf.navigationController pushViewController:attentionVC animated:YES];
                
            }else if (index == DailyInspection){//日常巡检
            
                DailyInspectionController * dailyInspetionVC = [[DailyInspectionController alloc]init];
                [self.navigationController pushViewController:dailyInspetionVC animated:YES];
                
            }else if (index == EquipmentManager){
            //设备管理
                EquipmentManagerController * equipmentVC = [[EquipmentManagerController alloc]init];
                [self.navigationController pushViewController:equipmentVC animated:YES];
                
            }else if (index == ParkingQuery)
            {//车位查询
                ParkingController * parkingVC = [[ParkingController alloc]init];
                
                [self.navigationController pushViewController:parkingVC animated:YES];
            }
            else if (index == OwnerInfoQuery)
            {//业主信息
            
//                AttentionController * attentionVC = [[AttentionController alloc]init];
//                attentionVC.title = @"业主信息查询";
//                attentionVC.tag = 310;
//                [weakSelf.navigationController pushViewController:attentionVC animated:YES];
                OwnweController * ownerVC = [[OwnweController alloc]init];
                
                [self.navigationController pushViewController:ownerVC animated:YES];
                
            }else if (index == HouseInfoQuery)
            {//房屋信息
                HouseInfoQueryController * houseInfoVC = [[HouseInfoQueryController alloc]init];

                houseInfoVC.buiddingID = self.buiddingID;
                    

                [self.navigationController pushViewController:houseInfoVC animated:YES];
            
            }else if (index == ChaoBiao){
            //抄表
                CheckFormController * checkFormVC = [[CheckFormController alloc]init];
                
                [self.navigationController pushViewController:checkFormVC animated:YES];
            
            }else if (index == ChaoBiaoQuery){
            //抄表查询
                FormQueryController * fromQueryVC = [[FormQueryController alloc]init];
                fromQueryVC.buidUnitID = self.buiddingID;
                [self.navigationController pushViewController:fromQueryVC animated:YES];
            }else if (index == PaymentQuery){
            //物业缴费查询
                ProprertyPayController * propretyPayVC = [[ProprertyPayController alloc]init];
                [self.navigationController pushViewController:propretyPayVC animated:YES];
            }else if (index == LeaderFrom){
                //领导报表
        
                LeaderController * leaderVC = [[LeaderController alloc]init];
                [self.navigationController pushViewController:leaderVC animated:YES];
        
            }else if (index == RepairQuery){
            //报修单查询
                RepairController * repairVC = [[RepairController alloc]init];
                [self.navigationController pushViewController:repairVC animated:YES];
            
            }
        
        };
        return menuCell;
    }

    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) {
        return 35;
    }else if (indexPath.section == 1)
    {
        return 155;
    }else if (indexPath.section == 2)
    {
    return 180;
        
    }
    return 45;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        return 10;
}
#pragma mark - 摇一摇点击事件
- (void)shakeAction:(UITapGestureRecognizer *)tap
{
    DLog(@"点击摇一摇");
    ShakeOpenController * shakeVC = [[ShakeOpenController alloc]init];
    [self.navigationController pushViewController:shakeVC animated:YES];
}
- (void)repairAction:(UITapGestureRecognizer *)tap
{
    DLog(@"点击报修单");
    
    HomeRepairController * repairVC = [[HomeRepairController alloc]init];
    [self.navigationController pushViewController:repairVC animated:YES];
}


- (void)complaintAction:(UITapGestureRecognizer *)tap
{
    DLog(@"点击投诉单");
    
    HomeComplainController * homeCompainVC = [[HomeComplainController alloc]init];

    [self.navigationController pushViewController:homeCompainVC animated:YES];
    
}
- (void)messageAction:(UITapGestureRecognizer *)tap
{
    DLog(@"点击消息");
    MessageController * messageVC = [[MessageController alloc]init];
    [self.navigationController pushViewController:messageVC animated:YES];
}
#pragma mark - 下拉选择小区代理
- (void)setupNavigationUI {
    SYNavigationDropdownMenu *menu = [[SYNavigationDropdownMenu alloc] initWithNavigationController:self.navigationController];
    menu.dataSource = self;
    menu.delegate = self;
    self.navigationItem.titleView = menu;
    
}

- (NSArray<NSString *> *)titleArrayForNavigationDropdownMenu:(SYNavigationDropdownMenu *)navigationDropdownMenu {
    return self.titleArray;
}

- (CGFloat)arrowPaddingForNavigationDropdownMenu:(SYNavigationDropdownMenu *)navigationDropdownMenu {
    return 8.0;
}

- (UIImage *)arrowImageForNavigationDropdownMenu:(SYNavigationDropdownMenu *)navigationDropdownMenu {
    return [UIImage imageNamed:@"ico_drop_down"];
}

- (void)navigationDropdownMenu:(SYNavigationDropdownMenu *)navigationDropdownMenu didSelectTitleAtIndex:(NSUInteger)index {
    
    //回调选择地址信息
   // self.label.text = self.titleArray[index];
    DLog(@"选择了 === %@",self.titleArray[index]);
   
}

#pragma mark - Property method

- (NSArray<NSString *> *)titleArray {
    
    return self.selectedCommunityNameArr;
   // return @[@"小区1",@"小区2",@"小区3"];
}
#pragma mark - 获取楼栋信息
- (void)postFloorQueryData
{
    NSDictionary * parms = @{
                             @"CommunityID":userModel.CommunityID,
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"getbuilding\",\"version\":\"V1.0\"}"};
    [HomeNetWorkRequest postFloorQuerySuccess:^(id data) {

        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        //DLog(@"楼栋信息的数据 == %@",array);
        
        NSDictionary *dic = array.firstObject;
        self.buiddingID = dic[@"BuildUnitId"];
        DLog(@"第一个id == %@",self.buiddingID);
        
        
        
    } Fail:^(NSString *errorDes) {
        
    } param:parms];
    
}
#pragma mark - 获取消息个数数据
- (void)postWorkNumData{
    
    NSDictionary * parms = nil;
    parms = @{
              @"WorkerId":userModel.WorkerID,
              @"CommunityID":userModel.CommunityID,
              @"json":@"\{\"jsonEntity\":\{},\"action\":\"incompletetask\",\"version\":\"V1.0\"}"
              };
    
    [WorkOrderRequest postWorkNumSuccess:^(id data) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"工单数量的数据 == %@",array);
        for (NSDictionary * dict in array) {
            
            self.complainttotalCount = dict[@"AllComplaintcount"];
            self.repairtotalCount = dict[@"AllRepaircount"];
            self.notReadNoticecount = dict[@"notReadNoticecount"];
            
            self.myComplaintcount = dict[@"MyComplaintcount"];
            self.myRepaircount = dict[@"MyRepaircount"];
            
            DLog(@"报修单数量 == %@",self.repairtotalCount);
        }
        
        NSDictionary * notiDict = @{@"key":self.complainttotalCount,@"key1":self.repairtotalCount,@"key2":self.myComplaintcount,@"key3":self.myRepaircount};
        [[NSNotificationCenter defaultCenter] postNotificationName:getTabbarNewsCountNoticeCenter object:nil userInfo:notiDict];
        
        
        [self.mTableView reloadData];
        
    } Fail:^(NSString *errorDes) {
        [MBProgressHUD hideHUD];
    } param:parms];
    
}
#pragma mark - 消息数据
- (void)postMessageData{
    
    NSDictionary * parms = @{
                             @"CommunityID":userModel.CommunityID,
                             @"Key":@"",
                             @"NoticeType":@"toplist",
                             @"UserID":@"0",
                             @"CurPage":@"1",
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"noticelist\",\"version\":\"V1.0\"}"};
    DLog(@"领导提交的参数===%@",parms);
    
    [HomeNetWorkRequest postHomeMessageSuccess:^(id data) {
        
        [self.messageArray removeAllObjects];
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"消息数据 == %@",array);
        
        DLog(@"%@",dict[@"Msg"]);
        
        
        for (NSDictionary * dict in array) {
            
            MessageModel * model = [[MessageModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            
            [self.messageArray addObject:model];
            
            [self.noticeTitleArr addObject:model.Title];
            DLog(@" 获取到的标题 === %@",model.Title);
        }
        
        [self.mTableView reloadData];
        
    } Fail:^(NSString *errorDes) {
        
        
        [MBProgressHUD hideHUD];
        
    } param:parms];
    
    
}
@end
